#!/bin/sh

APP=vscodium

# CREATE THE FOLDER
mkdir /opt/$APP
cd /opt/$APP

# ADD THE REMOVER
echo '#!/bin/sh' >> /opt/$APP/remove
echo "rm -R -f /usr/local/share/applications/AM-$APP.desktop /opt/$APP /usr/local/bin/$APP" >> /opt/$APP/remove
chmod a+x /opt/$APP/remove

# DOWNLOAD THE APPIMAGE
mkdir tmp
cd ./tmp

v=$(curl -Ls https://api.github.com/repos/VSCodium/vscodium/releases/latest | grep -E tag_name | awk -F '[""]' '{print $4}')
wget https://github.com/VSCodium/vscodium/releases/download/$v/VSCodium-linux-arm64-$v.tar.gz

version=$(ls /opt/$APP/tmp)
echo "$version" >> /opt/$APP/version

tar fx ./*.tar.gz
rm -f ./*.tar.gz
cd ..
mv ./tmp/* ./
rmdir ./tmp

# LINK
ln -s /opt/$APP/codium /usr/local/bin/$APP

# SCRIPT TO UPDATE THE PROGRAM
echo '#!/bin/sh' >> /opt/$APP/AM-updater
echo "APP=$APP" >> /opt/$APP/AM-updater
echo "cd /opt/$APP" /usr/local/bin/$APP
echo 'version0=$(cat /opt/$APP/version)

url=https://github.com/VSCodium/vscodium/releases/latest' >> /opt/$APP/AM-updater

echo 'if curl -L -s $url | grep -ioF "$version0"; then' >> /opt/$APP/AM-updater
echo '  echo "Update not needed!".'  >> /opt/$APP/AM-updater
echo 'else' >> /opt/$APP/AM-updater
echo "  notify-send 'A new version of $APP is available, please wait'" >> /opt/$APP/AM-updater
echo "  mkdir /opt/$APP/tmp
  cd /opt/$APP/tmp" >> /opt/$APP/AM-updater

########################################################################################

function1='$(curl -Ls https://api.github.com/repos/VSCodium/vscodium/releases/latest'
part0='{print $4}'
part1='[""]'
function2="grep -E tag_name | awk -F '$part1' '$part0')"
function3='$(ls /opt/$APP/tmp)'
function4='wget https://github.com/VSCodium/vscodium/releases/download/$v/VSCodium-linux-arm64-$v.tar.gz'

echo "  v=$function1 | $function2
  $function4
  version=$function3" >> /opt/$APP/AM-updater

########################################################################################

echo '  cd ..
  if test -f ./tmp/*tar.gz; then rm ./version
  fi
  echo "$version" >> ./version' >> /opt/$APP/AM-updater
echo "  tar fx ./tmp/*.tar.gz
  rm ./tmp/*.tar.gz
  mv ./tmp/* ./
  rmdir ./tmp
fi" >> /opt/$APP/AM-updater
chmod a+x /opt/$APP/AM-updater

# LAUNCHER
rm -f /usr/local/share/applications/AM-$APP.desktop
echo "[Desktop Entry]
Name=VSCodium
Comment=Code Editing. Redefined.
GenericName=Text Editor
Exec=vscodium --unity-launch %F
Icon=/opt/$APP/$APP.svg
Type=Application
StartupNotify=false
StartupWMClass=VSCodium
Categories=Utility;TextEditor;Development;IDE;
MimeType=text/plain;inode/directory;application/x-codium-workspace;
Actions=new-empty-window;
Keywords=vscode;

X-AppImage-Version=1.59.1-1629418630.glibc2.17

[Desktop Action new-empty-window]
Name=New Empty Window
Exec=vscodium --new-window %F
Icon=/opt/$APP/$APP.svg" >> /usr/local/share/applications/AM-$APP.desktop

# ICON
wget https://raw.githubusercontent.com/ivan-hc/AM-application-manager/main/programs/.icons/$APP/$APP.svg
